package com.tskj.leonsu.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tskj.leonsu.aop.annotation.SystemControllerLog;
import com.tskj.leonsu.dao.HairCutDAO;
import com.tskj.leonsu.utility.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author LeonSu
 */
@Service
public class HairCutService {

    @Autowired
    private HairCutDAO hairCutDAO;

    public JSONArray getBathRoomList() {
        return hairCutDAO.getHairCutRoomList();
    }

    public JSONArray getTimeList(String hairCutId, String date) {
        JSONArray allList = hairCutDAO.getTimeAndCountList(hairCutId, date);
        JSONArray retArray = new JSONArray();
        JSONObject data;
        for (Object obj : allList) {
            JSONObject json = (JSONObject) obj;
            data = new JSONObject();
            data.put("id", json.getString("tid"));
            data.put("timeTitle", String.format("%s - %s", Tools.getShortTime(json.getString("starttime")), Tools.getShortTime(json.getString("endtime"))));
            data.put("timeCount", json.getIntValue("hnum"));
            retArray.add(data);
        }
        return retArray;
    }

    @SystemControllerLog(MODULENAME = "理发")
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveOrder(JSONObject student, JSONObject data) {
        JSONObject retData = new JSONObject();

        String timeId = data.getString("id");
        String hairRoom = data.getString("hairCutRoom");
        String hairRoomId = data.getString("hairCutId");
        String newHairRoomId = hairCutDAO.getHairCutRoomId(hairRoom);
        if (!newHairRoomId.equalsIgnoreCase(hairRoomId)) {
            retData.put("code", 1);
            retData.put("errMsg", "数据不正确");
            return retData;
        }
        String dateString = data.getString("date");
        String timeString = data.getString("time");
        String startTime = timeString.split("-")[0].trim();
        String endTime = timeString.split("-")[1].trim();

        //TODO:保存前，需要检查当前时间是否已订满
        if (!hairCutDAO.canSave(hairRoom, startTime, endTime, 0, dateString)) {
            retData.put("code", 1);
            retData.put("errMsg", "当前时间已订满，请选择其他时间");
            return retData;
        }

        String adUserName = student.getString("username");
        try {
            //TODO：保存前，需要检查当前用户是否已有未完成订单
            if (!hairCutDAO.hasOrder(adUserName, Tools.today())) {
                retData.put("code", 1);
                retData.put("errMsg", "已创建过订单，请不要重复创建");
                return retData;
            }

            String sex = student.getString("sexy");
            int sexId = sex.equals("男") ? 1 : 0;
            String studentName = student.getString("studentname");
            String studentNo = student.getString("studentid");
            String xueYuan = student.getString("xueyuan");

            String bathSortNo = hairCutDAO.getHairCutSortNo(hairRoomId, hairRoom);
            String timeSortNo = hairCutDAO.getTimeSortNo(hairRoomId, timeId);
            String maxOrderNo = hairCutDAO.getMaxOrderNo(hairRoom, dateString, startTime, endTime);
            String code = String.format("%s-%s-%d%03d", bathSortNo, timeSortNo, sexId, Integer.valueOf(maxOrderNo));

            hairCutDAO.save(Tools.newId(), studentName, sex, Integer.valueOf(maxOrderNo), hairRoom, startTime, endTime, 0, code, dateString, adUserName);
            retData.put("code", 0);
            JSONObject detail = new JSONObject();
            retData.put("data", detail);
            student = new JSONObject();
            student.put("name", studentName);
            student.put("no", studentNo);
            student.put("xueyuan", xueYuan);
            student.put("sex", sex);
            detail.put("student", student);

            JSONObject order = new JSONObject();
            order.put("type", 2);
            order.put("address", hairRoom);
            order.put("date", dateString);
            order.put("time", timeString);
            order.put("code", code);
            detail.put("order", order);
            return retData;
        } catch (Exception e) {
            e.printStackTrace();
            retData.put("code", 1);
            retData.put("errMsg", "理发订单创建失败，请稍后重试");
            return retData;
        }
    }

    /**
     * 检查是否允许下订单，一是：8:00-16:00能下，二是如果该用户没有下过明天的订单
     *
     * @param userName
     * @param date
     * @return
     */
    public JSONObject checkStopTime(String userName, String date) {
        JSONObject ret = new JSONObject();
        ret.put("code", 0);
        String time = Tools.getNowTime();
        if (hairCutDAO.getOrderByAdUserName(userName, date) > 0) {
            ret.put("data", false);
        } else {
            ret.put("data", true);
            JSONObject setTimes = hairCutDAO.getStartTime();
            if (time.compareTo(setTimes.getString("start")) < 0 || time.compareTo(setTimes.getString("end")) > 0) {
                ret.put("data", false);
                ret.put("start", setTimes.getString("start"));
                ret.put("end", setTimes.getString("end"));
            }
        }
        return ret;
    }

    public JSONArray getUnFinishedOrder(String adUserName) {
        return hairCutDAO.getUnFinishedOrder(adUserName);
    }

    public JSONArray getFinishedOrder(String adUserName) {
        return hairCutDAO.getFinishedOrder(adUserName);
    }

    public JSONArray getAllOrder(String adUserName) {
        return hairCutDAO.getAllOrder(adUserName);
    }

    public void confirmOrder(String adUserName, String id) throws Exception {
        if (hairCutDAO.getCanConfirm(id)) {
            hairCutDAO.confirmOrder(adUserName, id);
        } else {
            throw new Exception("订单确认失败，未到允许订单确认时间");
        }
    }

    public void cancelOrder(String adUserName, String id) throws Exception {
        if (hairCutDAO.getCanCancel(id)) {
            hairCutDAO.cancelOrder(adUserName, id);
        } else {
            throw new Exception("订单取消失败，超过订单取消时间");
        }
    }

}
